
#include <memory>
#include <cassert>

#include <AEEStdErr.h>

#define FARF_HIGH 1
#include <HAP_farf.h>

#include "dlfcn.h"

#include "fastcv_aux.hpp"

static void *obj_fcvlib = NULL;

static FcvContext ctx;

FcvContext *FcvContext::getContext()
{
    return &ctx; 
}

FcvContext::FcvContext(): ref_cnt(0)
{
    // init();
}

FcvContext::~FcvContext()
{
    // deinit();    
}

int FcvContext::init()
{
    // Load the fastCV library
    // The library is part of the DSP image and will be available on the target
    if (obj_fcvlib == NULL) {
        obj_fcvlib = dlopen("libfastcvadsp.so", RTLD_NOW);
        if (obj_fcvlib == NULL) {
            FARF(ERROR,"Failed to open libfastcvadsp.so file ");
            return AEE_EUNABLETOLOAD;
        }
        ref_cnt = 1;
    } else {
        ref_cnt++;
        return 0;
    }

    LOAD_FUNC(fcvGetVersion);
    LOAD_FUNC(fcvMemAlloc);
    LOAD_FUNC(fcvMemFree);
    LOAD_FUNC(fcvSetOperationMode);
    LOAD_FUNC(fcvCleanUp);

    LOAD_FUNC(fcvScaleu8);
    LOAD_FUNC(fcvScaleDownBLu8);
    LOAD_FUNC(fcvAddScalarf32);
    LOAD_FUNC(fcvMultiplyScalarf32);
    LOAD_FUNC(fcvElementMultiplyf32);
    LOAD_FUNC(fcvMatrixMultiplyf32);
    LOAD_FUNC(fcvMatrixMultiplys8s32);

    LOAD_FUNC(fcvMinMaxLocf32);
    LOAD_FUNC(fcvMinMaxLocu8);
    LOAD_FUNC(fcvMinMaxLocs16);

    LOAD_FUNC(fcvTransposeu16);

    LOAD_FUNC(fcvFFTu8);
    LOAD_FUNC(fcvIFFTf32);
    LOAD_FUNC(fcvDCTu8);
    LOAD_FUNC(fcvIDCTs16);

    char ver[100] = {0};
    dl_fcvGetVersion(ver, sizeof(ver));
    FARF(HIGH, "fcv verstion: %s", ver);

    return 0;
}

void FcvContext::deinit()
{
    if (ref_cnt) {
        ref_cnt--;
        if (ref_cnt == 0) {
            dl_fcvCleanUp();
            if (obj_fcvlib) {
                dlclose(obj_fcvlib);
                obj_fcvlib = NULL;
            }
        }
    }

}

void *FcvContext::loadFunc(const char *name)
{
    if (!obj_fcvlib) {
        FARF(HIGH, "obj_fcvlib is not init!!");
        return nullptr;
    }
    return  dlsym(obj_fcvlib, name);
}







